/*
 * @(#)FileSysConfig.java   1.0  2021年12月24日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.loadconfig;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Component;

import com.swift.dts.loadconfig.model.SysConfig;
import com.swift.exception.extend.SystemException;
import com.swift.util.exec.PathUtil;
import com.swift.util.type.ByteUtil;
import com.swift.util.type.JsonUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2021年12月24日
 */
@Component
public class FileSysConfig {
    private static final String sysconfig_file = "/data/config/sysconfig.json";
    
    private volatile SysConfig sysConfig=null;
    
    public SysConfig read() {
        if(sysConfig==null) {
            sysConfig=JsonUtil.toObj(loadFile(), SysConfig.class);
        }
        if(sysConfig==null) sysConfig=new SysConfig();
        return sysConfig;
    }
    
    public synchronized void save(SysConfig sysConfig) {
        try {
            String json = JsonUtil.toJson(sysConfig);
            BufferedWriter out = new BufferedWriter(new FileWriter(PathUtil.findOnClassPath(sysconfig_file)));
            out.write(json);
            out.close();
            this.sysConfig=sysConfig;
        } catch (IOException e) {
            throw new SystemException("写"+PathUtil.findOnClassPath(sysconfig_file)+"文件失败",e);
        }
    }
    
    protected byte[] loadFile() {
        try {
            InputStream in = new FileInputStream(PathUtil.findOnClassPath(sysconfig_file));
            byte[] jsonByte = ByteUtil.inputToByte(in);
            try {
                in.close();
            } catch (IOException e) {
            }
            return jsonByte;
        } catch (Exception e) {
            throw new SystemException("读"+sysconfig_file+"文件失败",e);
        }
    }
}
